#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Project: kubeext-SDS 
@File: autoAdmTest.py
@Author: admin
@Date: 2022/6/9 9:57 
@desc: 
"""

from disk import *
from pool import *
from snap import *
from testconstant import KUBESDS_TEST_STORAGE_TYPE
from utils.constant.constant import VMDI
from utils.logger import set_logger

logger = set_logger(os.path.basename(__file__), KUBESDS_LOG)


def auto_test(pool_types):
    try:
        logger.debug('\n\n')
        logger.debug('***kubesds auto test start.')
        # 设置测试时，特有的环境变量内容
        os.environ[KUBESDS_TEST_ENV_KEY] = KUBESDS_TEST_ENV_VALUE

        # -----------------NFS备份服务器相关操作------------
        backup_server_uuid = get_random_uuid()
        backup_server = get_random_uuid()
        try:
            pool_operation(NFS, backup_server_uuid, backup_server, VMDI)
        except Exception as e:
            raise KubdesdsExecuteException('kubesdsTestError',
                                           'kubesds auto test error, backup server error.')
        # -----------------NFS备份服务器相关操作------------

        # -----------------NFS目标存储相关操作--------------
        target_pool_uuid = get_random_uuid()
        target_pool = get_random_uuid()
        try:
            pool_operation(NFS, target_pool_uuid, target_pool, VMD)
        except Exception as e:
            raise KubdesdsExecuteException('kubesdsTestError',
                                           'kubesds auto test error, target pool error.')
        # -----------------NFS目标存储相关操作--------------

        for pool_type in pool_types:
            if pool_type not in KUBESDS_TEST_STORAGE_TYPE:
                logger.error('***kubesds auto test error, pool type %s not in [%s].'
                             % (pool_type, KUBESDS_TEST_STORAGE_TYPE))
                continue
            # ---------------------存储相关操作---------------------
            pool_uuid = get_random_uuid()
            pool = get_random_uuid()
            pool_operation(pool_type, pool_uuid, pool, VMD)
            # ---------------------存储相关操作---------------------

            pool_info = get_cstor_pool(pool_uuid)
            target_pool_info = get_cstor_pool(target_pool_uuid)

            # ---------------------云盘相关操作---------------------
            disk_uuid = get_random_uuid()
            disk_operation(disk_uuid, pool_info, target_pool_info)
            # ---------------------云盘相关操作---------------------

            # ---------------------快照相关操作---------------------
            snap_uuid = get_random_uuid()
            snapshot_operation(disk_uuid, pool_info, snap_uuid, pool_uuid)
            # ---------------------快照相关操作---------------------

            # 删除云盘
            deleteDiskTest(disk_uuid, pool_info)
            # 删除存储
            deletePoolTest(pool_type, pool, pool_uuid)

        # 删除NFS目标存储
        deletePoolTest(NFS, target_pool, target_pool_uuid)
        # 删除NFS备份服务器
        deletePoolTest(NFS, backup_server, backup_server_uuid)

        logger.debug('***kubesds auto test end.')
        logger.debug('\n\n')

    except Exception as e:
        raise KubdesdsExecuteException('kubesdsTestError', 'kubesds auto test error.')
    finally:
        # 去除测试时特有的环境变量内容
        if KUBESDS_TEST_ENV_KEY in os.environ:
            del os.environ[KUBESDS_TEST_ENV_KEY]


def pool_operation(pool_type, pool_uuid, pool, content):
    """
    主存储/备份服务器/镜像服务器 相关操作（其中234操作仅限于localfs|nfs类型）：
    1. 创建主存储/备份服务器/镜像服务器;
    2. 显示主存储/备份服务器/镜像服务器
    :param pool_type: 主存储（localfs|nfs|ceph_dev类型），备份服务器（nfs类型），镜像服务器（nfs|ceph_dev类型）
    :param pool_uuid: 数据库中的msid值（界面上可以直接查看）
    :param pool: 表cl_hostlocalstorage_inf对应的poolname
    :param content: vmd: 主存储， vmdi: 备份服务器/镜像服务器
    :return:
    """
    # 1.创建主存储/备份服务器/镜像服务器（文件系统类型默认会开启，未设置自启动）
    createPoolTest(pool_type, pool_uuid, pool, content)
    # 2.显示主存储/备份服务器/镜像服务器
    showPoolTest(pool_type, pool)


def disk_operation(disk_uuid, pool_info, target_pool_info):
    """
    云盘相关操作：
    1.通过规格创建无分配策略的2G数据盘
    2.注册云盘至k8s中
    3.云盘路径检查
    4.云盘扩容
    5.显示云盘
    6.克隆云盘
    7.克隆完后随即进行删除
    8. 云盘迁移（测试后会重新迁回原存储），此处ceph-dev云盘不参与迁移
    :param disk_uuid: 云盘uuid
    :param pool_info: 通过cstor show-pool查询云盘所属存储所得信息
    :param target_pool_info: 目标存储信息，通过cstor show-pool查询云盘所属存储所得信息
    :return:
    """
    # 1.通过规格创建无分配策略的2G数据盘
    createDiskTest(disk_uuid, pool_info)
    # 2.注册云盘至k8s中
    registerDiskToK8sTest(disk_uuid, pool_info)
    # 3.云盘路径检查（此处针对云盘id进行云盘路径检查（此时vol必传），若针对路径进行检查（此时无需传vol，且path和pool_info必传））
    prepareDiskTest(domain=None, vol=disk_uuid, path=None)

    # 8. 云盘迁移（此处ceph-dev云盘不参与迁移）
    pool_type, pool = check_pool_info(pool_info)
    if pool_type != CEPH_DEV:
        migrateDiskTest(disk_uuid, pool_info, target_pool_info)
        # 迁移后，云盘迁移至原存储上
        migrateDiskTest(disk_uuid, target_pool_info, pool_info)

    # 4.云盘扩容（扩容至4G）
    resizeDiskTest(disk_uuid, pool_info)
    # 5.显示云盘
    showDiskTest(disk_uuid, pool_info)
    # 6.克隆云盘（本次克隆云盘只针对数据盘，不涉及系统盘），且克隆至原始云盘相同的存储池上
    clone_disk_uuid = get_random_uuid()
    cloneDiskTest(disk_uuid, pool_info, clone_disk_uuid)
    # 7.克隆完后随即进行删除
    deleteDiskTest(clone_disk_uuid, pool_info)


def snapshot_operation(disk_uuid, pool_info, snap_uuid, pool_name):
    """
    快照相关操作：
    1.创建云盘内部快照
    2.显示云盘内部快照
    3.恢复云盘内部快照
    4.删除云盘内部快照
    :param disk_uuid: 云盘uuid
    :param snap_uuid: 快照uuid
    :param pool_info: 通过cstor show-pool查询云盘所属存储所得信息
    :param pool_name: 云盘所属存储（此处对应的是数据库中的msid值（界面上可以直接查看），而非表cl_hostlocalstorage_inf对应的poolname）
    :return:
    """
    # 1.创建云盘内部快照（默认云盘未挂载云主机）
    createExternalSnapshotTest(disk_uuid, pool_info, snap_uuid, pool_name)
    # 2.显示云盘内部快照
    showDiskSnapshotTest(disk_uuid, pool_info, snap_uuid)
    # 3.恢复云盘内部快照
    revertExternalSnapshotTest(disk_uuid, pool_info, snap_uuid)
    # 4.删除云盘内部快照
    deleteExternalSnapshotTest(disk_uuid, pool_info, snap_uuid)


def main(args):
    params = vars(args)
    pool_types = params['type']
    if not pool_types:
        raise KubdesdsExecuteException('kubesdsTestError', 'type is none.')
    auto_test(pool_types)


if __name__ == '__main__':
    types = (NFS, )
    auto_test(types)
